package cn.pxs.service;

import cn.pxs.entity.*;
import cn.pxs.mapper.CartMapper;
import cn.pxs.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//购物车业务接口实现类
@Service
public class CartServiceImpl implements CartService{
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    OrdService ordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    //添加购物车
    public void add(Cart cart) {
        cartMapper.add(cart);
    }

    @Override
    //根据用户找购物车全查询
    public List<CartBook> findAll(Object user) {
        return cartMapper.findAll(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    //购物车转订单
    public  Order addCart2Order(Order o, List<OrdItem> ordItems) {
        Object user =
                SecurityContextHolder.getContext().getAuthentication().getPrincipal();//获取 用户信息
        List<Object> list = new ArrayList<>();
        for (int i = 0; i <ordItems.size(); i++) {
            //值进行添加 到 Order
            OrdItem  item = ordItems.get(i);
            //进行 总价 计算
            if(i==0 &&o.getAmount() == null){
                o.setAmount(item.getPrice()*item.getNum());
            }
            if(i!=0 && o.getAmount() != null){
                o.setAmount(o.getAmount()+(item.getPrice()*item.getNum()));
            }
            //添加创建时间
            o.setTcreate(new Date(new java.util.Date().getTime()));
        }
        for (int i = 0; i <ordItems.size(); i++) {
            //添加完值后 才进行添加
            OrdItem  item = ordItems.get(i);
            if(i==0){//Order只添加一次
                ordService.addOrd(user,o);//创建order
            }
            item.setOrdid(o.getOrdid());//ordid都一样
            cartMapper.addCart2Order(item);//创建order item
        }
        //返回的值
        Order order = ordService.findOrderByOrdid(o.getOrdid());
        return order;
    }
}
